<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\PrizeDraw;
use think\Config;
use think\Request;

/**
 * 砍运费
 */
class Cutfare extends Api
{
    protected $noNeedLogin = ['share'];
    protected $noNeedRight = ['*'];

    protected $model = null;


    protected $freight = 0;

    protected $gold   = 0;
    protected $silver = 0;
    protected $copper = 0;

    const TYPE_GOLD   = 1;         //类型1，金刀 新用户
    const TYPE_SILVER = 2;         //类型2，银刀 老用户
    const TYPE_COPPER = 3;          //类型3，铜刀 自己

    public function __construct()
    {
        parent::__construct();
        $this->model = new \app\common\model\Cutfare();

        //TODO 运费默认 10 通过后台设置
        if (Config::get('site.freight_fee') > 0){
            $this->freight = Config::get('site.freight_fee');
        }else{
            //免运费
            $this->freight = 0;
        }

        //金 银 铜 三刀 50 30 20比例 可后台配置
        $this->gold   = 0.5;
        $this->silver = 0.3;
        $this->copper = 0.2;
    }

    /**
     * 砍邮费 记录到 表中 3把刀 每把最多砍一次
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function cut()
    {
        //1 2 3
        $type = $this->request->request('type');
        $prize_draw_id = $this->request->request('pdid');

        if (!$type || !$prize_draw_id) $this->error('i18n:141');

        //金 银 铜 三刀 50 30 20比例 可后台配置
        if ($type == SELF::TYPE_GOLD) $rate = $this->gold;
        if ($type == SELF::TYPE_SILVER) $rate = $this->silver;
        if ($type == SELF::TYPE_COPPER) $rate = $this->copper;

        $user_id = $this->auth->id;

        //获取中奖记录
        $where = [
            'user_id'   => $user_id,
            'is_opened' => 1,
            'is_win'    => 1,
            'status'    => 0,
        ];
        $prizeDrawModel = new PrizeDraw();
        $prizeDrawData = $prizeDrawModel
            ->with(['goods'=>function($query){
                $query;
            }])
            ->where($where)
            ->find($prize_draw_id);

        if (!$prizeDrawData || $prizeDrawData['is_opened'] != 1 || $prizeDrawData['is_win'] != 1) {
            $this->error('i18n:139');
        }

        //虚拟商品无需砍运费
        if ($prizeDrawData['goods']['is_nomal_virtual'] == 2){
            $this->error('i18n:133');
        }

        //构造函数 获取后台设置的运费
        $freight = $this->freight;
        if ($freight == 0) $this->error('i18n:138');

        //获取是否有砍运费记录 金 银 铜 三刀 每刀只能砍一次
        $map = [
            'type'          => $type,
            'prize_draw_id' => $prize_draw_id,
        ];
        $cutfareData = $this->model
            ->where($map)
            ->find();

        if ($cutfareData && $cutfareData['user_id'] > 0){
            $this->error('i18n:140');
        }

        $param = [
            'type'      => $type,
            'prize_draw_id' => $prize_draw_id,
        ];

        //金 银 点就生成discount，需要分享后 新老用户 更新 userid，就是成功
        if (!$cutfareData){

            //金 银 铜 按比率生成砍邮费
            $discount = 0;
            $total = $freight * $rate * 100;
            if ($total > 0){
                $discount = mt_rand(1,$total) / 100;
                $param['discount'] = round($discount,2);
            }

            //铜刀存自己的user_id
            if ($type == SELF::TYPE_COPPER) {
                //自己的userid
                $param['user_id'] = $user_id;
            }

            $result = $this->model->save($param);
            if (!$result) $this->error('i18n:136');
        }else{
            $discount = $cutfareData['discount'];
        }

        //金刀 银刀 返回分享链接
        $url = '';
        if ($type != SELF::TYPE_COPPER){
            $request = Request::instance();
            $domain = $request->domain();
            $url = $domain . '/api/cutfare/share?type=' . $type . '&pdid='.$prize_draw_id;
        }

        //已砍次数 默认3次
        $count = $this->model->where([
            'prize_draw_id' => $prize_draw_id,
        ])->count();

        $data = [
            'type'      => $type,
            'discount'  => $discount,
            'url'       => $url,
            'redidue'   => 3 - $count,
        ];

        $this->success('i18n:62',$data);
    }

    public function helpCut(){

        $prize_draw_id = $this->request->request('pdid');

        //获取中奖记录 判断是否有效
        $where = [
            'id'    => $prize_draw_id,
        ];

        $prizeDrawModel = new PrizeDraw();
        $prizeDrawData = $prizeDrawModel
            ->with(['goods'=>function($query){
                $query;
            }])
            ->where($where)
            ->find();

        if (!$prizeDrawData || $prizeDrawData['is_opened'] != 1 || $prizeDrawData['is_win'] != 1) {
            $this->error('i18n:139');
        }

        if ($prizeDrawData['status'] != 0){
            $this->error('i18n:134');
        }

        //虚拟商品无需砍运费
        if ($prizeDrawData['goods']['is_nomal_virtual'] == 2){
            $this->error('i18n:133');
        }

        //构造函数 获取后台设置的运费
        $freight = $this->freight;
        if ($freight == 0) $this->error('i18n:138');

        //判断用户新老用户
        $user_id = $this->auth->id;

        //根据加入时间 判断新老用户
        $jointime = $this->auth->jointime;

        if ($jointime > strtotime('-3 day')){
            //新用户 金刀
            $type = SELF::TYPE_GOLD;
        }else{
            //老用户 银刀
            $type = SELF::TYPE_SILVER;
        }

        if ($type == SELF::TYPE_GOLD) $rate = $this->gold;
        if ($type == SELF::TYPE_SILVER) $rate = $this->silver;
        if ($type == SELF::TYPE_COPPER) $rate = $this->copper;

        //获取是否有砍运费记录 金 银 铜 三刀 每刀只能砍一次
        $map = [
            'type'          => $type,
            'prize_draw_id' => $prize_draw_id,
        ];
        $cutfareData = $this->model
            ->where($map)
            ->find();

        if ($cutfareData && $cutfareData['user_id'] > 0){
            $this->error('i18n:137');
        }

        $param = [
            'user_id'   => $user_id,
            'type'      => $type,
            'prize_draw_id' => $prize_draw_id,
        ];

        //金 银 点就生成discount，需要分享后 新老用户 更新 userid，就是成功
        if (!$cutfareData){

            //金 银 铜 按比率生成砍邮费
            $discount = 0;
            $total = $freight * $rate * 100;
            if ($total > 0){
                $discount = mt_rand(1,$total) / 100;
                $param['discount'] = round($discount,2);
            }

            $result = $this->model->save($param);
            if (!$result) $this->error('i18n:136');
        }

        $data = [
            'discount' => $param['discount'],
        ];
        $this->success('i18n:135',$data);
    }

    public function share(){
        $prize_draw_id = $this->request->request('pdid');

        //获取中奖记录
        $where = [
            'id'   => $prize_draw_id,
            'is_opened' => 1, //已开奖
            'is_win'    => 1, //已中奖
            'status'    => 0, //未领奖
        ];
        $prizeDrawModel = new PrizeDraw();
        $prizeDrawData = $prizeDrawModel
            ->with(['user'=>function($query){
                $query->field('id,nickname');
            }])
            ->with(['goods'=>function($query){
                $query->field('id,name,price,image,is_nomal_virtual');
            }])
            ->field('id,prize_id,user_id,opentime,goods_id,is_opened,is_win')
            ->where($where)
            ->find();

        if (!$prizeDrawData || $prizeDrawData['is_opened'] != 1 || $prizeDrawData['is_win'] != 1) {
            $this->error('i18n:134');
        }

        //虚拟商品无需砍运费
        if ($prizeDrawData['goods']['is_nomal_virtual'] == 2){
            $this->error('i18n:133');
        }

        //获取参与该抽奖的领奖人数
        $map = [
            'prize_id'  => $prizeDrawData['prize_id'],
            'opentime'  => $prizeDrawData['opentime'],
            'status'    => 1,
        ];
        $total = $prizeDrawModel
            ->where($map)
            ->count();

        $prizeDrawData['total'] = $total;

        //获取自动弃奖时间配置 也是过期时间
        $auto_giveup_time = Config::get('site.auto_giveup_time');
        $giveUpTime = 0;
        if ($auto_giveup_time > 0){
            $giveUpTime = $auto_giveup_time * 60 * 60;
        }else{
            //不自动弃奖
        }

        $prizeDrawData['goods']['image'] = getRealUrl($prizeDrawData['goods']['image']);
        //自动弃奖时间，也是这里朋友帮砍的过期时间
        $prizeDrawData['countdown'] = $prizeDrawData['opentime'] + $giveUpTime - time();

        $this->success('i18n:62',$prizeDrawData);
    }

    public function query()
    {
        $prize_draw_id = $this->request->request('pdid');

        $where = [
            'prize_draw_id'  => $prize_draw_id,
            'user_id'        => ['>',0]
        ];
        $cutFareModel = new \app\common\model\Cutfare();
        $cutfareData = $cutFareModel
            ->with(['user'=>function($query){
                $query->field('id,nickname');
            }])
            ->where($where)
            ->select();

        $discount = 0;
        foreach ($cutfareData as $k => $v){
            $discount += $v['discount'];
        }

        $freight_fee = $this->freight - $discount;
        $data = [
            'freight_fee'   =>  $freight_fee,
            'discount'   =>  $discount,
            'redidue'   => 3 - count($cutfareData),
            'cutfare' => $cutfareData,
        ];
        $this->success('i18n:62',$data);
    }

}
